package org.yufan.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.yufan.bean.Item;
import org.yufan.bean.ItemDesc;
import org.yufan.common.JedisService;
import org.yufan.exception.CustomException;
import org.yufan.rpc.service.ItemRpcService;
import org.yufan.service.ItemService;
import org.yufan.utils.HttpClientUtil;
import org.yufan.utils.JsonUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zxd on 2018/3/28.
 */
@Service
public class ItemServiceImpl2 implements ItemService{
    private Logger LOGGER= LoggerFactory.getLogger(ItemServiceImpl2.class);

    //商品详情的请求地址
    private static final String ITEM_DESC_UTL="http://manage.yufan.com/rest/rpc/item/queryItemDesc";

    @Autowired
    private JedisService jedisService;

    @Autowired
    private ItemRpcService itemRpcService;

    @Override
    public Item queryItemById(Long itemId) throws IOException, CustomException {
        //1.先从缓存中获取，如果缓存中没有在请求后台系统通过dubbo
        String json=jedisService.hget("item",itemId+"");
        if(StringUtils.isEmpty(json)){
            //从后台获取
            Item item = itemRpcService.queryItemById(itemId);
            //放到缓存中
            if(item==null){
                LOGGER.error("后台服务器调用异常{}",itemId);
                throw  new CustomException("后台服务器调用异常");
            }
            jedisService.hset("item",itemId+"",JsonUtils.objectToJson(item));
            return item;
        }
        //缓存中的数据转换成对象
        return JsonUtils.jsonToPojo(json,Item.class);
    }

    //改动
    @Override
    public ItemDesc queryItemDescById(Long itemId) throws IOException {
        //前台系统调用后台系统的接口
        //准备参数
        Map param=new HashMap<>();
        param.put("itemId",itemId+"");
        String json = HttpClientUtil.doPost(ITEM_DESC_UTL, param);
        LOGGER.info("调用的接口地址是:{},参数:{}",ITEM_DESC_UTL,itemId);
        LOGGER.debug("返回的结果是{}------------------.",json);

        ObjectMapper objectMapper=new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(json);
        JsonNode data = jsonNode.get("data");
        String item_desc_data=data.toString();
        LOGGER.debug("item:{}",item_desc_data);
        ItemDesc itemDesc = JsonUtils.jsonToPojo(item_desc_data, ItemDesc.class);
        return itemDesc;
    }
}
